package test.zookeeper;

import java.io.IOException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class App {
	
	static ZooKeeper  zk;
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
		String zkServer = "10.255.53.151:2181,10.255.53.152:2181,10.255.53.150:2181";
        
        zk = new ZooKeeper(zkServer,6000,new Watcher(){
                @Override
                public void process(WatchedEvent event) {                        
                }
        });
        zk.addAuthInfo("digest", "fengjr:fengjr.com".getBytes());  
        System.out.println("\ntestDir1的子节点列表为："+zk.getChildren("/fengjr-fengfd", true)); 
        //取出子节点列表
        String root = "/fengjr-fengfd/task";
        recur(root);
        
      //取出子节点列表
        System.out.println("\ntestDir1的子节点列表为："+zk.getChildren("/fengjr-fengfd", true)); 
                        
//        //取出节点的数据
//        System.out.println("\n取出/testDir1/sub1节点的数据为：" + new String(zk.getData("/testDir1/sub1", false, null)));
//                        
//        //修改节点数据
//        zk.setData("/testDir1/sub1", "sub3".getBytes(),-1);
//        System.out.println("\n取出/testDir1/sub1节点的数据为(修改后)：" + new String(zk.getData("/testDir1/sub1", false, null)));
//
//        //删除节点
//        System.out.println("\n删除节点/testDir1/sub1");                
//        zk.delete("/testDir1/sub1", -1);        
//        
//        System.out.println("\ntestDir1的子节点列表为：" + zk.getChildren("/testDir1", true));
	}
	
	static void recur(String root) throws InterruptedException, KeeperException {
		List<String> list = zk.getChildren(root, true); 
		System.out.println(list);
		for(String s : list) {
    		List<String> list2 = zk.getChildren(root + "/" + s, true);
    		if(CollectionUtils.isEmpty(list2)) {
    			zk.delete(root + "/" + s, -1);
    		} else {
    			recur(root + "/" +s);
    		}
    	}
	}

}
